package ie.dkit.java3Demulation.drawer;

import ie.dkit.java3Demulation.objects.Ellipse;
import ie.dkit.java3Demulation.objects.Point;
import ie.dkit.java3Demulation.objects3d.Circle3D;
import ie.dkit.java3Demulation.objects3d.Point3D;
import ie.dkit.java3Demulation.transforming.Transformer;

import java.awt.Graphics;

public class Circle3DDrawer extends EllipseDrawer {

	public Circle3DDrawer(Graphics graphics, int xMiddle, int ymiddle) {
		super(graphics, xMiddle, ymiddle);
	}

	public void draw(Circle3D circle3D) {
		synchronized (circle3D) {
			double rightRadius, topRadius, adjacent, opposite, radAngle1, radAngle2, angle;
			Point3D point3D1, point3D2;

			// Calculate the right radius of the eclipse
			adjacent = Math.abs(circle3D.getM_FacingPoint().getZ()
					- circle3D.getM_CenterPoint().getZ());
			opposite = Math.abs(circle3D.getM_FacingPoint().getX()
					- circle3D.getM_CenterPoint().getX());
			point3D1 = new Point3D(circle3D.getM_CenterPoint().getX()
					+ circle3D.getM_Radius(), circle3D.getM_CenterPoint()
					.getY(), circle3D.getM_CenterPoint().getZ());
			if (adjacent == 0 || opposite == 0) {
				radAngle1 = 0;
			} else {
				radAngle1 = Math.atan(opposite / adjacent);
			}

			// Calculate the top radius
			adjacent = Math.abs(circle3D.getM_FacingPoint().getZ()
					- circle3D.getM_CenterPoint().getZ());
			opposite = Math.abs(circle3D.getM_FacingPoint().getY()
					- circle3D.getM_CenterPoint().getY());
			point3D2 = new Point3D(circle3D.getM_CenterPoint().getX(), circle3D
					.getM_CenterPoint().getY()
					+ circle3D.getM_Radius(), circle3D.getM_CenterPoint()
					.getZ());
			if (adjacent == 0 || opposite == 0) {
				Transformer.rotateY(point3D1, Math.toDegrees(radAngle1));
				radAngle2 = 0;
			} else {
				radAngle2 = Math.atan(opposite / adjacent);
				Transformer.rotateY(point3D1, Math.toDegrees(radAngle1));
				Transformer.rotateX(point3D2, Math.toDegrees(radAngle2));
			}
			topRadius = point3D2.getY();
			rightRadius = point3D1.getX();

			// Calculate the angle
			adjacent = Math.abs(circle3D.getM_FacingPoint().getX()
					- circle3D.getM_CenterPoint().getX());
			opposite = Math.abs(circle3D.getM_FacingPoint().getY()
					- circle3D.getM_CenterPoint().getY());
			if (adjacent == 0 || opposite == 0) {
				angle = 0;
			} else {
				angle = Math.toDegrees(Math.atan(opposite / adjacent));
			}
			draw(new Ellipse(new Point(circle3D.getM_CenterPoint().getX(),
					circle3D.getM_CenterPoint().getY()), (int) rightRadius,
					(int) topRadius, angle));
		}
	}

}
